package com.hugh.lagoucloudgateway9002.filter;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.hugh.lagoucloudgateway9002.util.IpLimitUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Author: Hugh
 * @Date: 2020/7/24
 */
@Slf4j
@Component  // 让容器扫描到，等同于注册了
public class IpLimitFilter implements GlobalFilter, Ordered {

    @Autowired
    private IpLimitUtil ipLimitUtil;

    private static long periodInMillis = 10*1000;
    private static Integer limitCount = 10;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        Entry entry = null;
        try  {
            entry = SphU.entry("IpLimitFilter.filter");
            String ip = request.getRemoteAddress().getHostString();
            Boolean limited = ipLimitUtil.isLimited(ip, periodInMillis, limitCount);
            if (limited) {
                log.error("ip {} 存在恶意访问的嫌疑，已被限制", ip);
                String data = "Request be denied!";
                DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
                return response.writeWith(Mono.just(wrap));
            }
            log.info("通过的有效IP地址{}", ip);
        }catch (BlockException ex) {
            log.info("sentinel限流IpLimitFilter 生效");
        } finally {
            if (entry != null) {
                entry.exit();
            }
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
